﻿using UnityEngine;
using Core;
using ET;

public class Spawning : MonoSingleton<Spawning>
{
    [SerializeField]private  bool isRunting = false;
    [SerializeField]private  MapLevelConfig levelConfig;
    [SerializeField] private float time;

    private const float DoublePI = Mathf.PI * 2f;
    private const float hallPI = Mathf.PI / 2f;

    public void StartSpawning(MapLevelConfig mapLevelConfig)
    {
        levelConfig = mapLevelConfig;
        time = mapLevelConfig.intervalTimer;
        isRunting = true;
    }

    public void Stop()
    {
        isRunting = false;
    }

    private void Update()
    {
        if (!isRunting || levelConfig == null)
            return;

        time -= Time.deltaTime;

        if (time <= 0)
        {
            Generate().Coroutine();
            time = levelConfig.intervalTimer;
        }
    }

    async ETTask Generate()
    {
        var player = Player.Instance.GetParent<Unit>();
        var position = player.Position;
        for (int i = 0; i < levelConfig.count; i++)
        {
            var unit = await EnemyHelper.Create(levelConfig);
            unit.Position = position + RandomPosition(20);
        }
    }

    Vector3 RandomPosition(float radius)
    {
        float angle = Random.Range(0f, DoublePI) - hallPI; 
        float x = radius * Mathf.Cos(angle);
        float y = radius * Mathf.Sin(angle);
        float hallRadius = radius / 4f;
        return new Vector3(x + Random.Range(-hallRadius, hallRadius), 0, y + Random.Range(-hallRadius, hallRadius));
    }
}
